﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Framework.Exceptions.RepositoryExceptions;
using HelperTools;
using Interfaces.Criteria;
using Interfaces.Filters;
using Interfaces.Models;
using Interfaces.Providers;
using Interfaces.Repositories;
using Interfaces.RepositoryModels.InternalModels.EconomicInformationModels;

namespace SQLRepositories.EconomicRepositories
{
    public class CompanyRepository : EntityBaseRepository<CompanyModel>, ICompanyRepository, IEconomicDataProvider<IEnumerable<ICompany>, ICompanyFilter, IKeySupportedCriteria>
    {
        public CompanyRepository(IDBEconomicInformationServiceContext context) 
            : base(context)
        {}

        public void Create(CompanyModel item)
        {
            Context.Companies.Add(item);
            Context.SaveChanges();
        }

        public CompanyModel GetById(Guid id)
        {
          return (from company in Context.Companies 
                  where company.Id.Equals(id) 
                  select company).FirstOrDefault();
        }

        public void Delete(Guid id)
        {
            var removedItem = Context.Companies.FirstOrDefault(x => x.Id.Equals(id));
            if(removedItem == null)
                throw new EntityNotFoundException("Company");
            Context.Companies.Remove(removedItem);
            Context.SaveChanges();
        }

        public void Delete(CompanyModel item)
        {
            Context.Companies.Remove(item);
            Context.SaveChanges();
        }

        public IEnumerable<CompanyModel> GetAll()
        {
            return Context.Companies;
        }

        public IEnumerable<ICompany> GetData(IKeySupportedCriteria criteria, ICompanyFilter filter)
        {
            if (filter == null)
                throw new ArgumentNullException("filter");
            if (criteria == null)
                throw new ArgumentNullException("criteria");
            
            IEnumerable<CompanyModel> source = from comp in Context.Companies
                                               where criteria.Identificators.Contains(comp.Symbol)
                                               select comp;
            RepositoryMappingHelper.ResetMapping();
            RepositoryMappingHelper.CreateQuoteMapping();
            RepositoryMappingHelper.CreateCompanyMapping(criteria.IsFullLoading,filter.With(x=>x.QuoteisFilter));

            var result = Mapper.Map<IEnumerable<CompanyModel>, IEnumerable<ICompany>>(source);

            return filter.Filtrate(result) as IEnumerable<ICompany>;
        }
    }
}
